package com.autoai.util

import java.io.IOException
import java.util

import org.apache.http.client.ClientProtocolException
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.impl.client.{DefaultHttpClient}
import org.apache.http.message.BasicNameValuePair
import org.apache.http.params.CoreConnectionPNames
import org.apache.http.util.EntityUtils
import org.slf4j.LoggerFactory

import scala.reflect.macros.ParseException

object HttpClientUtils {

  val logger = LoggerFactory.getLogger("out")

  def get(url: String): String = {
    val httpclient = new DefaultHttpClient()
    try {
      // 创建httpget.
      val httpget = new HttpGet(url)
      httpget.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)
      httpget.getParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);
      // 执行get请求.
      val response = httpclient.execute(httpget)

      try {
        // 获取响应实体
        val entity = response.getEntity()
        EntityUtils.toString(entity, "utf-8")
      }
    } catch {
      case ex: ClientProtocolException => {logger.error(ex.getMessage);null}
      case ex: ParseException => {logger.error(ex.getMessage);null}
      case ex: IOException => {logger.error(ex.getMessage);null}
    }
    finally {
      // 关闭连接,释放资源
      httpclient.close()
    }
  }

}
